# -*- coding: utf-8 -*-
# @time: 2024/6/6 15:30
# @file: stock_bondpremium
# @author: tyshixi08

from get_data.origin_data import *

# 获取转债转股价值和纯债价值
def conversion_value_pure_bond_value(code = code_ls(), start_date = month_ls()[0] + '-01', end_date = month_ls()[-1] + '-01'):
    df = convertible.get_indicators(code, start_date, end_date, fields = ['conversion_value', 'pure_bond_value_1']).reset_index()
    return df

# 平底溢价率计算
def prem_cal(code = code_ls(), start_date = month_ls()[0] + '-01', end_date = month_ls()[-1] + '-01'):
    df = conversion_value_pure_bond_value(code, start_date, end_date)
    df['stock_bondpremium'] = df['conversion_value'] / df['pure_bond_value_1'] - 1
    df = df[['order_book_id', 'date', 'stock_bondpremium']]
    return df

# 获取转债平底溢价率中位数
def stock_bondpremium_median(code = code_ls(), start_date = month_ls()[0] + '-01', end_date = month_ls()[-1] + '-01'):
    df = prem_cal(code, start_date, end_date)
    df_stock_bondpremium = df.groupby('date')['stock_bondpremium'].median().reset_index().rename(columns={'stock_bondpremium':'stock_bondpremium_mid'})
    return df_stock_bondpremium.sort_values('date')

# 数据存档
def stock_bondpremium_mid_save():
    excel_file_path = 'stock_bondpremium_mid.csv'
    #if os.path.exists('原始数据/' + excel_file_path):
    #    df = pd.read_csv('原始数据/' + excel_file_path)
    #    return df
    #else:
    save_CSV(stock_bondpremium_median(), 'get_data/原始数据/' + excel_file_path.split('.')[0])
    df = pd.read_csv('get_data/原始数据/' + excel_file_path)
    return df

